import n from "./AudioManager"
import l from "./PlayerDataSys"
import s from "./PeripheralSystemDataMgr"
import c from "./EventMgr"
import u from "./GameEventType"
import p from "./frameworkManager"
import d from "./ScrollViewCtrl"
import h from "./EngineUtil"
import f from "./BasePageCtrl"
import g from "./PageMgr"
import y from "./PeripheralSystemMgr"
import m from "./UiManage"
import _ from "./FundWithDrawBanPage"

const { ccclass, property } = cc._decorator;
@ccclass
export default class FundWithDrawBanPageCtrl {
    @property(cc.Prefab)
    prefabUrl: string = "FundWithDrawBanPage";

    @property(cc.Label)
    cashLabel: cc.Label = null;

    private ui: any;
    private gold_balance: number;
    private extract_info: any;
    private city_info: any;
    private click_index: number;

    onLoad() {
        this.onUILoad();
        this.dealAnimType();
        this.addButtonListen();
        this.addEvent();
    }

    start() { }

    _init(data) {
        if (data) {
            const { gold_balance, extract_info, city_info } = data;
            this.gold_balance = gold_balance;
            this.extract_info = extract_info;
            this.city_info = city_info;
            this.cashLabel.string = this.getCashBalance(this.gold_balance) + "元";
            this.initGear();
            this.addTravelPorgress();
            this.checkGuide();
            this.clickGender(this.ui.option_0);
        }
    }

    checkGuide() {
        const step = s.getOutsideGuideStep();
        if (step ==OutSideLevelGuide.FUND_GUIDE) {
            this.scheduleOnce(() => {
                const audio = "outsideLevel_guide_" + step;
                n.getInstance().playMusic(audio);
                g.showPage("NoviceFundrewardPage");
            }, 1);
            if (g.hasShowPage("OutsideLevelGuidePage")) {
                g.hidePage("OutsideLevelGuidePage");
            }
            this.ui.fundNode.active = true;
            this.ui.btn_close.getComponent(cc.Button).interactable = false;
            this.ui.btn_weChatPayment.getComponent(cc.Button).interactable = false;
            this.ui.maskNode.active = true;
        } else if (step ==OutSideLevelGuide.FUND_PROVICE) {
            this.ui.fundNode.active = true;
            this.ui.btn_close.getComponent(cc.Button).interactable = false;
            this.ui.btn_weChatPayment.getComponent(cc.Button).interactable = true;
            this.ui.maskNode.active = true;
            this.ui.guide_hand.active = true;
            this.ui.goldCount.getComponent(cc.Label).string = this.getCashBalance(l.gold_balance) + "元";
            if (g.hasShowPage("OutsideLevelGuidePage")) {
                g.hidePage("OutsideLevelGuidePage");
            }
        } else {
            n.getInstance().playMusic("fund_withDraw_tip");
            this.ui.fundNode.active = true;
            this.ui.goldCount.getComponent(cc.Label).string = this.getCashBalance(l.gold_balance) + "元";
            this.ui.maskNode.active = false;
            this.ui.guide_hand.active = false;
            this.ui.btn_close.getComponent(cc.Button).interactable = true;
            this.ui.btn_weChatPayment.getComponent(cc.Button).interactable = true;
        }
    }

    addEvent() {
        c.listen(u.UPDATE_FUND, this.updateFund, this);
        c.listen(u.FUND_AMPLIFY, this.playFundNodeAction, this);
    }

    removeEvent() {
        c.ignore(u.UPDATE_FUND, this.updateFund, this);
        c.ignore(u.FUND_AMPLIFY, this.playFundNodeAction, this);
    }

    updateFund() {
        this.ui.btn_close.getComponent(cc.Button).interactable = false;
        const startPos = cc.v2(0, 0);
        const endPos = this.ui.fundNode.getPosition().add(cc.v2(-90, 30));
        const self = this;
        this.updatenNumberAnim(() => {
            c.trigger(u.SHOWEFFECT_FLYINGRED, {
                startPos,
                endPos,
                type: 1,
                callback: () => {
                    self.ui.goldCount.getComponent(cc.Label).string = this.getCashBalance(l.gold_balance) + "元";
                    self.ui.btn_weChatPayment.getComponent(cc.Button).interactable = true;
                }
            });
        });
    }

    playFundNodeAction() {
        cc.tween(this.ui.fundNode)
            .to(0.05, { scale: 1.1 })
            .to(0.05, { scale: 1 })
            .call(() => {
                this.ui.fundNode.scale = 1;
            })
            .start();
    }

    initGear() {
        const children = this.ui.optionNode.children;
        for (let i = 0; i < children.length; i++) {
            const child = children[i];
            this.addListen(child, this.clickGender, this);
        }
    }

    onUILoad() {
        this.ui = this.node.addComponent(_);
    }

    addButtonListen() {
       UiManager.addButtonListen(this.ui.btn_close, this.clickClose, this);
       UiManager.addButtonListen(
            this.ui.btn_weChatPayment,
            this.clickWechatPayment,
            this
        );
    }

    clickGender(target) {
        const name = target.name;
        const index = parseInt(name.replace(/[^0-9]/gi, ""));
        if (this.click_index !== index) {
            this.click_index = index;
            this.showOneSelect(name);
            this.showTips();
        }
    }

    showOneSelect(name) {
        const children = this.ui.optionNode.children;
        for (let i = 0; i < children.length; i++) {
            const child = children[i];
            const common = child.getChildByName("common");
            const select = child.getChildByName("select");
            if (child.name === name) {
                common.active = false;
                select.active = true;
            } else {
                common.active = true;
                select.active = false;
            }
        }
    }

    addListen(target, callback, context, eventName = "click") {
        if (target && target.getComponent(cc.Button)) {
            target.on(eventName, () => {
                n.getInstance().playMusic(eventName);
                if (callback) {
                    callback.bind(context)(target);
                }
            }, context);
        }
    }

    clickClose() {
        this.hide();
        if (s.getOutsideGuideStep() !==OutSideLevelGuide.FUND_GUIDE) {
            n.getInstance().stopMusic("fund_withDraw_tip", false);
        }
    }

    addTravelPorgress() {
        this.ui.content.removeAllChildren();
        if (!this.city_info || (this.city_info && this.city_info.length === 0)) {
            p.log("城市进度为空");
        } else {
            this.ui.scrollView.getComponent(d).init(this.city_info);
            this.ui.scrollView.getComponent(d).scrollTotop();
        }
    }

    clickWechatPayment() {
        if (s.getOutsideGuideStep() !=OutSideLevelGuide.FUND_PROVICE) {
            if (this.click_index !== null) {
                const e = this.extract_info[this.click_index].conditions;
                const t = e[0].finish;
                const a = e[1];
                const o = e[2];
                if (parseInt(this.gold_balance) < parseInt(t)) {
                    h.showManageViewToast("旅行基金不足不能提现");
                } else if (a.status !== 0) {
                    if (o.status !== 0) {
                        h.showManageViewToast("旅行基金提现异常");
                    } else {
                        g.showPage("FundWithDrawConditionPage", {
                            conditional: o,
                            type: 2,
                            gold_balance: this.gold_balance
                        });
                    }
                } else {
                    g.showPage("FundWithDrawConditionPage", {
                        conditional: a,
                        type: 1,
                        gold_balance: this.gold_balance
                    });
                }
            } else {
                h.showManageViewToast("没有选择旅行基金提现档位");
            }
        } else {
            s.setOutsideStep(y.OutSideLevelGuide.CLICK_WITHDRAW);
            y.reportOutsideGuideStep(y.OutSideLevelGuide.CLICK_WITHDRAW);
            g.showPage("OutsideLevelGuidePage");
            this.hide();
        }
    }

    showTips() {
        if (this.click_index !== null) {
            const e = this.extract_info[this.click_index].conditions[0].finish;
            const t = this.getCashBalance(e);
            this.ui.goldCount.getComponent(cc.Label).string = `${t}元`;
        }
    }

    getCashBalance(e) {
        let t = 0;
        try {
            t = Number(e) / 100;
        } catch (e) {
            p.log("金额格式化出错：", e);
        }
        return t.toFixed(2);
    }

    hide() {
        g.hidePage("FundWithDrawBanPage");
    }

    ngOnDestroy() {
        this.removeEvent();
       UiManager.removeButtonListen(this.ui.btn_close, this.clickClose, this);
       UiManager.removeButtonListen(
            this.ui.btn_weChatPayment,
            this.clickWechatPayment,
            this
        );
    }

    updatenNumberAnim(callback) {
        const oriCash = parseInt(this.ui.goldCount.getComponent(cc.Label).string.split("元")[0]);
        const newCash = parseInt(this.gold_balance);
        const perCash = Math.floor((newCash - oriCash) / 30);
        let cnt = 30;
        this.schedule(() => {
            cnt--;
            if (cnt > 0) {
                oriCash += perCash;
                this.ui.goldCount.getComponent(cc.Label).string = `${oriCash}元`;
            } else {
                this.ui.goldCount.getComponent(cc.Label).string = `${newCash / 100}元`;
                callback();
                this.unscheduleAllCallbacks();
            }
        }, 0.02);
    }

    dealAnimType() {
        // 处理不同平台进入时的特效显示
        if (c.isWxgame()) {
            this.ui.anim_2.active = false;
            this.ui.anim_1.active = true;
        } else {
            this.ui.anim_1.active = false;
            this.ui.anim_2.active = true;
        }
    }
}